package com.aia.prm.web.ria.app.ui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Date;
import java.util.UUID;

import com.aia.prm.BeanFactory;
import com.aia.prm.web.ria.app.PrmApplication;
import com.cfh.domain.User;
import com.vaadin.data.Item;
import com.vaadin.data.Validator;
import com.vaadin.data.util.BeanItem;
import com.vaadin.data.validator.StringLengthValidator;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Component;
import com.vaadin.ui.DefaultFieldFactory;
import com.vaadin.ui.Field;
import com.vaadin.ui.Form;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.PasswordField;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window;

@SuppressWarnings("serial")
public class ChangePasswordDialog extends Window implements Button.ClickListener {
	PrmApplication app;
	final Form personForm;
	Person person;

	public ChangePasswordDialog(PrmApplication application) {
		this.app = application;

		setCaption("修改密码");
		setWidth("260px");
		// setResizable(false);
		setModal(true);

		VerticalLayout root = new VerticalLayout();
		root.setSpacing(true);
		root.setMargin(true);
		setContent(root);

		root.addComponent(new Label("*修改密码之后需要重新登录"));
		// form = new Form();
		person = new Person(); // a person POJO
		BeanItem<Person> personItem = new BeanItem<Person>(person);

		// Create the Form
		personForm = new Form();
		personForm.setCaption("表单");
		personForm.setWriteThrough(false); // we want explicit 'apply'
		personForm.setInvalidCommitted(false); // no invalid values in datamodel

		// FieldFactory for customizing the fields and adding validators
		personForm.setFormFieldFactory(new PersonFieldFactory());
		personForm.setItemDataSource(personItem); // bind to POJO via BeanItem

		// Determines which properties are shown, and in which order:
		personForm.setVisibleItemProperties(Arrays.asList(new String[] { "oldpassword", "password", "password2" }));

		root.addComponent(personForm);
		HorizontalLayout winButtons = new HorizontalLayout();
		winButtons.setSpacing(true);

		winButtons.addComponent(new Button("确定", this));

		winButtons.addComponent(new Button("取消", new Button.ClickListener() {
			public void buttonClick(Button.ClickEvent event) {
				ChangePasswordDialog.this.getParent().removeWindow(ChangePasswordDialog.this);
			}
		}));

		root.addComponent(winButtons);
		root.setComponentAlignment(winButtons, Alignment.BOTTOM_CENTER);
	}

	private class PersonFieldFactory extends DefaultFieldFactory {

		public PersonFieldFactory() {
		}

		@Override
		public Field createField(Item item, Object propertyId, Component uiContext) {
			Field f;
			if (propertyId != null && propertyId.toString().contains("password")) {
				f = createPasswordField(propertyId);
			} else {
				f = super.createField(item, propertyId, uiContext);
			}
			return f;
		}

		private PasswordField createPasswordField(Object propertyId) {
			PasswordField pf = new PasswordField();
			if (propertyId.equals("oldpassword")) {
				pf.setCaption("原密码");
			} else if (propertyId.equals("password")) {
				pf.setCaption("新密码");
			} else if (propertyId.equals("password2")) {
				pf.setCaption("再输入一次");
			}
			pf.addValidator(new StringLengthValidator("Password must be 6-20 characters", 6, 20, false));
			pf.setRequired(true);
			pf.setRequiredError("不能为空");
			return pf;
		}
	}

	public class Person implements Serializable {

		private String firstName = "";
		private String lastName = "";
		private Date birthdate;
		private Integer shoesize = 42;
		private String oldpassword = "";
		private String password = "";
		private String password2 = "";
		private UUID uuid;
		private String countryCode = "";

		public Person() {
			uuid = UUID.fromString("3856c3da-ea56-4717-9f58-85f6c5f560a5");
		}

		public String getFirstName() {
			return firstName;
		}

		public void setFirstName(String firstName) {
			this.firstName = firstName;
		}

		public String getLastName() {
			return lastName;
		}

		public void setLastName(String lastName) {
			this.lastName = lastName;
		}

		public Date getBirthdate() {
			return birthdate;
		}

		public void setBirthdate(Date birthdate) {
			this.birthdate = birthdate;
		}

		public Integer getShoesize() {
			return shoesize;
		}

		public void setShoesize(Integer shoesize) {
			this.shoesize = shoesize;
		}

		public String getPassword() {
			return password;
		}

		public void setPassword(String password) {
			this.password = password;
		}

		public UUID getUuid() {
			return uuid;
		}

		public String getCountryCode() {
			return countryCode;
		}

		public void setCountryCode(String countryCode) {
			this.countryCode = countryCode;
		}

		public String getOldpassword() {
			return oldpassword;
		}

		public void setOldpassword(String oldpassword) {
			this.oldpassword = oldpassword;
		}

		public String getPassword2() {
			return password2;
		}

		public void setPassword2(String password2) {
			this.password2 = password2;
		}

	}

	public class IntegerValidator implements Validator {

		private String message;

		public IntegerValidator(String message) {
			this.message = message;
		}

		public boolean isValid(Object value) {
			if (value == null || !(value instanceof String)) {
				return false;
			}
			try {
				Integer.parseInt((String) value);
			} catch (Exception e) {
				return false;
			}
			return true;
		}

		public void validate(Object value) throws InvalidValueException {
			if (!isValid(value)) {
				throw new InvalidValueException(message);
			}
		}
	}

	public void buttonClick(ClickEvent event) {

		boolean isValidate = true;
		try {
			personForm.commit();
		} catch (Exception e) {
			// Ignored, we'll let the Form handle the errors
			isValidate = false;
			return;
		}
		User user = (User) app.getUser();

		if (!person.getPassword2().equals(person.getPassword())) {
			app.getMainWindow().showNotification("两次输入的密码不一致", Notification.TYPE_WARNING_MESSAGE);
			isValidate = false;
			return;
		}

		if (!person.getOldpassword().equals(user.getPASSWORD())) {
			app.getMainWindow().showNotification("原密码输入错误", Notification.TYPE_WARNING_MESSAGE);
			isValidate = false;
			return;
		}

		if (isValidate) {
			BeanFactory.get().getDefaultService().changePassword(user, person.getPassword());
			// app.getMainWindow().showNotification("处理成功！");
			ChangePasswordDialog.this.getParent().removeWindow(ChangePasswordDialog.this);
			// app.close();
			AlertDialog.confirmYesNo(app, "修改成功，请点击确定重新登录", new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					app.close();
				}
			});
		}
	}
}
